package com.chahua.organized.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.chahua.organized.common.PageData;
import com.chahua.organized.constant.CommonConstant;
import com.chahua.organized.dao.DepartmentDao;
import com.chahua.organized.entity.Department;
import com.chahua.organized.entity.DepartmentMember;
import com.chahua.organized.dao.DepartmentMemberDao;
import com.chahua.organized.exception.DepartmentMemberException;
import com.chahua.organized.handler.MemberImportVerifyHandler;
import com.chahua.organized.qo.DepartmentMemberInput;
import com.chahua.organized.qo.DepartmentMemberMoveQo;
import com.chahua.organized.qo.DepartmentMemberPageQo;
import com.chahua.organized.qo.DepartmentMemberQo;
import com.chahua.organized.service.DepartmentMemberService;
import com.chahua.organized.service.DepartmentService;
import com.chahua.organized.vo.DepartmentMemberInfoVo;
import com.chahua.organized.vo.DepartmentMemberInputVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service("departmentMemberService")
public class DepartmentMemberServiceImpl implements DepartmentMemberService {

    @Autowired
    private DepartmentMemberDao departmentMemberDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private MemberImportVerifyHandler memberImportVerifyHandler;

    /**
     * 添加成员
     * @param departmentMemberQo    数据
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(DepartmentMemberQo departmentMemberQo) {
        // 1、保存成员的基本信息
        DepartmentMember departmentMember = new DepartmentMember();
        BeanUtils.copyProperties(departmentMemberQo, departmentMember);

        // 2、校验姓名+手机号是否重复
        int count = departmentMemberDao.findByNameAndPhone(departmentMemberQo.getName(),departmentMemberQo.getPhone());
        if(count>0){
            throw new DepartmentMemberException("name.and.phone.is.not.allow.repeatable");
        }

        // 3、如果所属部门为空，则将人员添加到默认部门下
        if(Objects.isNull(departmentMemberQo.getDeptId())){
            Integer rootDeptId = departmentDao.findIdByPidAndName(CommonConstant.BUILT_IN_ROOT_DEPARTMENT_PARENT_ID,"部门");
            Integer defaultDeptId = departmentDao.findIdByPidAndName(rootDeptId, "默认部门");
            departmentMember.setDeptId(defaultDeptId);
        }
        departmentMember.setCreateTime(new Date());
        departmentMember.setUpdateTime(new Date());
        departmentMemberDao.insert(departmentMember);
    }

    /**
     * 查询成员信息
     * @param id      主键
     * @return    DepartmentMemberInfoVo
     */
    @Override
    public DepartmentMemberInfoVo getMemberById(Integer id) {
        DepartmentMemberInfoVo departmentMemberInfoVo = new DepartmentMemberInfoVo();
        // 1、查询基本信息：id,name,deptId,isManager,post,phone,email,createTime,updateTime
        DepartmentMember departmentMember = departmentMemberDao.findById(id);
        if (Objects.isNull(departmentMember)) {
            throw new DepartmentMemberException("department.member.is.not.exist");
        }
        BeanUtils.copyProperties(departmentMember, departmentMemberInfoVo);

        // 2、查询所属部门层级路径名称：deptPath
        List<Integer> deptPathIds = departmentService.getDepartmentPath(departmentMember.getDeptId());
        List<String> deptPath = deptPathIds.stream().map(deptPathId -> {
            return departmentDao.findById(deptPathId).getName();
        }).collect(Collectors.toList());
        departmentMemberInfoVo.setDeptPath(deptPath);
        return departmentMemberInfoVo;
    }

    /**
     * 分页查询成员列表
     * @param departmentMemberPageQo     查询条件
     * @return   PageData<DepartmentMemberInfoVo>
     */
    @Override
    public PageData<DepartmentMemberInfoVo> listWithPage(DepartmentMemberPageQo departmentMemberPageQo) {
        // 分页查询条件
        PageData<DepartmentMemberInfoVo> pageData = new PageData<>();
        PageHelper.startPage(departmentMemberPageQo.getPageNum(), departmentMemberPageQo.getPageSize());

        // 根据部门查询/根据姓名模糊查询
        List<Integer> memberIdList = departmentMemberDao.findAllByCondition(departmentMemberPageQo);
        List<DepartmentMemberInfoVo> departmentMemberVoList = memberIdList.stream().map(this::getMemberById).collect(Collectors.toList());
        PageInfo<DepartmentMemberInfoVo> pageInfo = new PageInfo<>(departmentMemberVoList);
        pageData.addPageInfo(pageInfo);
        return pageData;
    }

    /**
     * 更新成员信息
     * @param id   主键
     * @param departmentMemberQo   数据
     */
    @Override
    public void updateMemberById(Integer id, DepartmentMemberQo departmentMemberQo) {
        DepartmentMember departmentMember = departmentMemberDao.findById(id);
        if(Objects.isNull(departmentMember)){
            throw new DepartmentMemberException("department.member.is.not.exist");
        }
        BeanUtils.copyProperties(departmentMemberQo,departmentMember);
        departmentMemberDao.updateById(departmentMember);
    }

    /**
     * 删除成员
     * @param ids  成员ids
     */
    @Override
    public void delete(List<Integer> ids) {
        departmentMemberDao.batchDelete(ids);
    }

    /**
     * 移动成员部门
     * @param departmentMemberMoveQo  数据
     */
    @Override
    public void move(DepartmentMemberMoveQo departmentMemberMoveQo) {
        departmentMemberDao.updateByIds(departmentMemberMoveQo.getIds(),departmentMemberMoveQo.getDeptId());
    }

    /**
     * 下载excel模板文件
     * @param response response
     * @param request request
     */
    @Override
    public void download(HttpServletResponse response, HttpServletRequest request) {
        ClassPathResource classPathResource = new ClassPathResource("excel/test.xlsx");
        ServletOutputStream servletOutputStream = null;
        InputStream inputStream = null;
        try {
            inputStream = classPathResource.getInputStream();
            String filename = "excel导入模板";
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(filename.getBytes(), StandardCharsets.ISO_8859_1) + ".xls");
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public DepartmentMemberInputVo importMember(MultipartFile multipartFile, HttpServletResponse resp) {
        // 校验文件类型和文件大小
        checkFileSizeAndType(multipartFile);
        ExcelImportResult<DepartmentMemberInput> result;
        ImportParams params = new ImportParams();
        DepartmentMemberInputVo departmentMemberInputVo = null;
        try {
            // 表头设置为1行
            params.setHeadRows(1);
            // 标题设置为1行，标题不会导入，相当于去除标题行
            params.setTitleRows(1);
            // 开启Excel校验
            params.setNeedVerify(true);
            // 使用自定义校验类
            params.setVerifyHandler(memberImportVerifyHandler);
            result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(), DepartmentMemberInput.class, params);
            // 获取excel导入数据
            List<DepartmentMemberInput> importMemberList = result.getList();

            // 将数据存入数据库
            saveMemberToDB(importMemberList);

            departmentMemberInputVo = new DepartmentMemberInputVo();
            // 导入失败的条数
            departmentMemberInputVo.setFailCount(result.getFailList().size());
            // 导入成功的条数
            departmentMemberInputVo.setSuccessCount(result.getList().size());

            // 验证是否有失败的数据
            if (result.isVerfiyFail()) {
                ServletOutputStream servletOutputStream = resp.getOutputStream();
                //mime类型
                resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                resp.setHeader("Content-disposition", "attachment;filename=error.xls");
                result.getFailWorkbook().write(servletOutputStream);
                servletOutputStream.close();
            }
        } catch (Exception e) {
            throw new DepartmentMemberException("excel.import.member.error");
        } finally {
            // 清除threadLocal 防止内存泄漏
            ThreadLocal<List<DepartmentMemberInput>> threadLocal = memberImportVerifyHandler.getThreadLocal();
            if (threadLocal != null) {
                threadLocal.remove();
            }
        }
        return departmentMemberInputVo;
    }


    /**
     * 校验文件类型和文件大小
     * @param multipartFile 上传的excel文件
     */
    private void checkFileSizeAndType(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            throw new DepartmentMemberException("file.name.is.not.allow.null");
        }
        if(fileName.endsWith("xls") || fileName.endsWith("xlsx")){
            if(multipartFile.getSize() / 1024 / 1024 > 5){
                throw new DepartmentMemberException("the.file.size.can.not.exceed.5M");
            }
        }else{
            throw new DepartmentMemberException("incorrect.file.type");
        }
    }

    /**
     * 保存导入的成员信息
     * @param importMemberList 成员数据
     */
    private void saveMemberToDB(List<DepartmentMemberInput> importMemberList) {
        for(DepartmentMemberInput departmentMemberInput:importMemberList){
            // 保存部门成员基本信息
            DepartmentMember departmentMember = new DepartmentMember();
            BeanUtils.copyProperties(departmentMemberInput,departmentMember);
            departmentMember.setCreateTime(new Date());
            departmentMember.setUpdateTime(new Date());
            // 设置部门id
            String deptNameImport = departmentMemberInput.getDepartment().getName();
            Integer rootId = departmentDao.findByPidAndName(CommonConstant.BUILT_IN_ROOT_DEPARTMENT_PARENT_ID,"部门");
            Integer defaultDeptId = departmentDao.findByPidAndName(rootId, "默认部门");
            if(StringUtils.isEmpty(deptNameImport)){
                departmentMember.setDeptId(defaultDeptId);
            }else{
                String deptName = departmentMemberInput.getDepartment().getName();
                int deptId = getDeptId(deptName);
                if(deptId==-1){
                    departmentMember.setDeptId(defaultDeptId);
                }
                departmentMember.setDeptId(deptId);
            }
            departmentMemberDao.insert(departmentMember);
        }
    }

    /**
     * 根据excel导入的部门信息获取部门id
     * @param deptName 数据
     * @return 部门id
     */
    public int getDeptId(String deptName) {
        String[] deptPathNameImport  = deptName.split("/");
        int index = deptPathNameImport.length-1;
        // 根据最后一级部门名称查找部门
        List<Department> departmentList = departmentDao.findByName(deptPathNameImport[index]);
        if(CollectionUtils.isEmpty(departmentList)){
            return -1;
        }
        for(Department department:departmentList){
            // 暂存deptId
            int deptId = department.getId();
            // 如果当前部门的父级部门不是0，寻找部门的父级部门
            while (index > 0 && department!=null && department.getPid() != 0){
                department = departmentDao.findById(department.getPid());
                if(department!=null && !department.getName().equals(deptPathNameImport[--index])){
                    // 如果父级部门不等于excel中导入的父级部门
                    break;
                }
                if(index==0){
                    return deptId;
                }
            }
        }
        return -1;
    }
}
